$(document).ready(function(){
	// Round the corners of the outermost frame
	$(".bnt_outline_top").corners("12px top-left top-right no-native");
	$(".bnt_outline_bottom").corners("12px bottom-left bottom-right no-native");
	
	// Left main menu accordion functionality
	$("#bnt_main_menu").accordion({
		header: "a.bnt_accmenu",
		active: false,
		autoHeight: false,
		collapsible: true,
		alwaysOpen: false
	});
	
	// Store title attribute for menu links on hover
	$("a[id^='menu'],a[id^='accmenu'],div[id^='accmenu'],.planet_menu_button,#planet_button_frame,#returnto_planet_menu,#reset_ptransfer").live("mouseover", function() {
		title = $(this).attr("title");
		$(this).attr("title","");
		$(this).addClass("bnt_hover_pointer");
	});
	$("a[id^='menu'],a[id^='accmenu'],div[id^='accmenu'],.planet_menu_button,#planet_button_frame,#returnto_planet_menu,#reset_ptransfer").live("mouseout", function() {
		$(this).attr("title",title);
		$(this).removeClass("bnt_hover_pointer");
	});
	
	// Accordion main menu links
	$("div[id^='accmenu'],a[id^='accmenu']").live("click", function () {
		$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;" + title + ";xml");
    });
	
	// Non-Accordion main menu links
	$("a[id^='menu']").live("click", function () {
		$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;" + title + ";xml");
		$("#bnt_main_menu").accordion("activate" , false);
    });
	
	// Toggle planet selling
	$(".planet_sells").live("click", function () {
		var sellid = $(this).children("input").val();
		$(this).html("<img src='" + smf_images_url + "/bnt/ajax-loader-small.gif' />");
		$(this).load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=planet_report_ce;sellid=" + sellid + ";xml");
    });
	
	// Planet check all checkbox
	$("#planet_checkall").live("click", function () {
		$(":checkbox").attr("checked", $("#planet_checkall").is(":checked"));
	});
	
	// Planet rename
	$(".planet_rename").live("click", function () {
		var planet_name = $(this).html();
		$(this).closest("li").html("<input type='text' class='planet_rename_field' value='" + planet_name + "' />");
	});
	$(".planet_rename_field").live("keypress", function (e) {
		var c = e.which ? e.which : e.keyCode;
		if (c == 13)
		{
			var planet_name = $(this).val()
			var planet_id = $(this).closest("tr").attr("id");
			if (planet_name.length > 0)
			{
				$(this).attr("disabled", true);
				$(this).closest("li").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=planet_report_ce;planet_name=" + escape(planet_name) + ";planet_id=" + planet_id + ";xml");
			}
			else if (planet_name.length > 25)
			{
				alert("Name cannot be longer than 25 characters")
			}
			else
			{
				alert("Please enter a planet name");
			}
		}
	});
	$(".planet_rename_field").live("change", function (e) {
		var planet_name = $(this).val()
		var planet_id = $(this).closest("tr").attr("id");
		if (planet_name.length > 0)
		{
			$(this).attr("disabled", true);
			$(this).closest("li").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=planet_report_ce;planet_name=" + escape(planet_name) + ";planet_id=" + planet_id + ";xml");
		}
		else if (planet_name.length > 25)
		{
			alert("Name cannot be longer than 25 characters")
		}
		else
		{
			alert("Please enter a planet name");
		}
	});
	
	// Build a base
	$("#build_base").live("click", function () {
		var buildp = $(this).children("#buildp").val();
		var builds = $(this).children("#builds").val();
		$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=planet_report_ce;buildp=" + buildp + ";builds=" + builds + ";xml", function() {
			$("#turns_available").html($("#collect_credits_turns_available").val());
			$("#turns_used").html($("#collect_credits_turns_used").val());
		});
	});
	
	// Collect all credits from check planets
	$("#collect_credits_engage").live("click", function () {
		var id = $("input[name='credits_planet_id']:checkbox").fieldArray();
		var planets = "";
		
		if (id == "")
		{
			alert("Please select at least one planet");
		}
		else
		{
			for (i = 0; i < id.length; i++)
			{
				planets = planets + id[i] + ",";
			}
			planets = planets.substring(0, planets.length-1);
			$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
			$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=planet_report_ce;planets=" + planets + ";xml", function() {
				$("#turns_available").html($("#collect_credits_turns_available").val());
				$("#turns_used").html($("#collect_credits_turns_used").val());
				$("#cargo_credits").html($("#collect_credits_balance").val());
			});
		}
	});
	
	// Change planetary from the report menu production or an individual planet
	$("#change_production").live("click", function () {
		// Determine if this being run from the report menu of an individual planet
		if ($("#planet_status_frame").length > 0)
		{
			var source = "planet";
			var planet_id = $("#planet_id").val();
			var target = "action=blacknova;sa=planet;planet_id=" + planet_id + ";xml"
		}
		else
		{
			var source = "report";
			var target = "action=blacknova;sa=planet_report;PRepType=2;xml"
		}
		
		if (source == "report")
		{
			// Verify and get Global Production Changes
			// Global production change order is ore, organics, goods, energy, fighters, torps
			$.GPC = {
				querystring: "global_production_changes=",
				check_percentages: 0,
				proderror: false
			}
			$("input[id^='global_setting_']").each(function() {
				$.GPC.prodnumber = $(this).val();
				if ($.GPC.prodnumber.length == 0)
				{
					$.GPC.prodnumber = 0
				}
				
				if (isPositiveInteger($.GPC.prodnumber) && $.GPC.prodnumber >= 0 && $.GPC.prodnumber <= 100)
				{
					$.GPC.querystring = $.GPC.querystring + $.GPC.prodnumber + ",";
					$.GPC.check_percentages = $.GPC.check_percentages + ($.GPC.prodnumber - 0);
				}
				else
				{
					$.GPC.proderror = "Invalid character in global production values";
					return false;
				}
			});
			$.GPC.querystring = $.GPC.querystring.substring(0, $.GPC.querystring.length-1);
			
			if ($.GPC.check_percentages < 0 || $.GPC.check_percentages > 100)
			{
				$.GPC.proderror = "Global production value greater than 100%";
			}
		}
		// Set proderror to false so we can initiate the planet production changes when coming from the planet screen
		else
		{
			$.GPC = {
				proderror: false
			}
		}

		if ($.GPC.proderror == false || source == "planet")
		{
			// Verify and get Planetary Production Changes
			// Production change order is Planet id, global setting, ore, organics, goods, energy, fighters, torps
			// Each planet productions value is seperated by a "-"
			$.PPC = {
				querystring: "production_changes=",
				proderror: false,
				check_percentages: 0
			}
			
			$("#planet_production_table > tbody > tr").each( function() {
				// Make sure this is NOT a secondary header row before processing
				if (!($(this).is(".second_header")))
				{
					$.PPC.querystring = $.PPC.querystring + $(this).attr("id") + ",";
					$.PPC.check_percentages = 0;

					// Step through each cell and look for an input field
					$(this).children("td").each( function() {
						// Check for the global checkbox
						if ($(this).children().is("input:checkbox"))
						{
							if ($(this).children().attr("checked"))
							{
								$.PPC.querystring = $.PPC.querystring + "true" + ",";
							}
							else
							{
								$.PPC.querystring = $.PPC.querystring + "false" + ",";
							}
						}
						else if ($(this).children().is("input:text")) {
							$.PPC.prodnumber = $(this).children().val();
							if ($.PPC.prodnumber.length == 0)
							{
								$.PPC.prodnumber = 0
							}
							
							if (isPositiveInteger($.PPC.prodnumber) && $.PPC.prodnumber >= 0 && $.PPC.prodnumber <= 100)
							{
								$.PPC.querystring = $.PPC.querystring + $.PPC.prodnumber + ",";
								$.PPC.check_percentages = $.PPC.check_percentages + ($.PPC.prodnumber - 0);
							}
							else
							{
								$.PPC.proderror = "Invalid character in planetary production values";
								return false;
							}
						}
					});
				
					// Add a "-" seperator if we are changes multiple planets at once
					if (source == "report")
					{
						$.PPC.querystring = $.PPC.querystring.substring(0, $.PPC.querystring.length - 1);
						$.PPC.querystring = $.PPC.querystring + "-";
					}
					
					// Check for invalid percentage values
					if ($.PPC.check_percentages < 0 || $.PPC.check_percentages > 100)
					{
						$.PPC.proderror = "Planetary production value greater than 100%";
						return false;	
					}
				}
			});
			
			$.PPC.querystring = $.PPC.querystring.substring(0, $.PPC.querystring.length - 1);
			
			if (source == "report")
			{
				$.PPC.querystring = $.PPC.querystring + ";" + $.GPC.querystring;
			}
			
			if ($.PPC.proderror == false)
			{
				$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
				$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=planet_report_ce;" + $.PPC.querystring + ";xml", function() {
					$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
					$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + target);
				});
			}
			else
			{
				alert($.PPC.proderror);
			}
		}
		else
		{
			alert($.GPC.proderror);
		}	
	});
	
	// Planet production global enable/disable
	$(".global_toggle").live("click", function () {
		if ($(this).attr("checked"))
		{
			var planet_id = $(this).attr("name");
			$("." + planet_id).attr("disabled", true);
			$("." + planet_id).addClass("bnt_disabled");
		}
		else
		{
			var planet_id = $(this).attr("name");
			$("." + planet_id).removeAttr("disabled");
			$("." + planet_id).removeClass("bnt_disabled");
		}
	});
	
	// Load an individual planet view
	$(".planet_view").live("click", function () {
		$(this).append("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		var planet_id = $(this).children("input").val();
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=planet;planet_id=" + planet_id + ";xml");
	});
	
	// Planet display link button
	$("#planet_display_frame").live("click", function () {
		var planet_id = $("#on_planet_id").val();
		$("#planet_display_frame").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=planet;planet_id=" + planet_id + ";xml");
		$("#bnt_main_menu").accordion("activate", false);
	});
	
	// Planet action buttons
	$(".planet_menu_button,#planet_button_frame,#returnto_planet_menu,#reset_ptransfer").live("click", function () {
		var planet_id = $("#planet_id").val();
		var querystring = "action=blacknova;sa=planet;planet_id=" + planet_id + ";";
		
		// Check if this is action requires a dialog
		if ($(this).children("#planet_dialog").length > 0)
		{
			var dialog_title = $(this).children("#planet_dialog").val();
			$("#planet_dialog").attr("title",dialog_title);
			$("#planet_dialog").load(smf_prepareScriptUrl(smf_scripturl) + querystring + title + ";xml").dialog({ 
				modal: true,
				buttons: {	"Cancel": function() { 
										$(this).dialog("close"); 
										$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
										$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + querystring + "xml");
									},
							"Confirm": function() {
										// Check for new planet name
										if ($("#planet_newname").length > 0)
										{
											querystring = querystring + "planet_newname=" + $("#planet_newname").val() + ";";
										}
										$(this).dialog("close");
										$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
										$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + querystring + title + ";confirm=yes;xml");
									}
				}
			});
		}
		else
		{
			// Check if this a scan planet command
			if ($("#planetcommand_scan").length > 0)
			{ 
				$(".planet_status_data").html("Scanning . . ."); 
			}
			
			// Check if we are trading resources
			if ($("#planet_trade_table").length > 0)
			{ 
				var trade_ore = $("#trade_ore").val();
				var trade_organics = $("#trade_organics").val();
				var trade_goods = $("#trade_goods").val();
				var trade_energy = $("#trade_energy").val();
				querystring = querystring + "trade_ore=" + trade_ore + ";trade_organics=" + trade_organics + ";trade_goods=" + trade_goods + ";trade_energy=" + trade_energy + ";";
			}
			
			// Process the command
			$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + querystring + title + ";xml", function () {
				// Check if we need to update the turns display
				if ($("#planet_turns_available").length > 0)
				{ 
					$("#turns_available").html($("#updated_turns_available").val()); 
				}
				if ($("#planet_turns_used").length > 0)
				{ 
					$("#turns_used").html($("#updated_turns_used").val()); 
				}
				
				// Check if we need to update the ship cargo and credit display
				if ($("#planet_trade_result").length > 0)
				{ 
					$("#cargo_ore").html($("#ship_ore").val());
					$("#cargo_organics").html($("#ship_organics").val());
					$("#cargo_goods").html($("#ship_goods").val());
					$("#cargo_energy").html($("#ship_energy").val());
					$("#cargo_credits").html($("#ship_credits").val());
				}
			});
		}
	});
	
	// Extract planetary transfer values and initiate transfer
	$("#initiate_ptransfer").live("click", function () {
		var planet_id = $("#planet_id").val();
		var querystring = "action=blacknova;sa=planet;command=transfer;transfer_request=true;planet_id=" + planet_id + ";" + $("#ptransfer").serialize();
		
		// Process the command
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + querystring + ";xml", function () {
			// Check if we need to update the turns display
			if ($("#planet_turns_available").length > 0)
			{ 
				$("#turns_available").html($("#updated_turns_available").val()); 
			}
			if ($("#planet_turns_used").length > 0)
			{ 
				$("#turns_used").html($("#updated_turns_used").val()); 
			}
			
			// Check if we need to update the ship cargo and credit display
			if ($("#ptransfer_result_frame").length > 0)
			{ 
				$("#turns_available").html($("#updated_turns_available").val());
				$("#turns_used").html($("#updated_turns_used").val()); 
				$("#cargo_ore").html($("#ship_ore").val());
				$("#cargo_organics").html($("#ship_organics").val());
				$("#cargo_goods").html($("#ship_goods").val());
				$("#cargo_energy").html($("#ship_energy").val());
				$("#cargo_colonists").html($("#ship_colonists").val());
				$("#cargo_credits").html($("#ship_credits").val());
				$("#armament_fighters").html($("#ship_fighters").val());
				$("#armament_torps").html($("#ship_torps").val());
			}
		});
	});
	
	// On hover effects for the sector display link
	$(".bnt_button, .lrs_button, .scan_button, .warp_old_button, .rs_button").live("mouseover", function() {
		$(this).addClass("ui-state-hover");
	});
	$(".bnt_button, .lrs_button, .scan_button, .warp_old_button, .rs_button").live("mouseout", function() {
		$(this).removeClass("ui-state-hover");
	});
	
	// On hover effects for the galaxy display map
	$(".galaxy_link").live("mouseover", function() {
		$(this).addClass("bnt_hover_pointer");
	});
	$(".galaxy_link").live("mouseout", function() {
		$(this).removeClass("bnt_hover_pointer");
	});
	
	// Sector display link button
	$("#sector_display_frame").live("click", function () {
		$("#sector_display_frame").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=main;xml");
		$("#bnt_main_menu").accordion("activate" , false);
	});
	
	// Sector scan buttons
	$(".scan_button, .lrs_button").live("click", function () {
		$("#maindisplay_right").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		var sector = $(this).children("input").val();
		$("#maindisplay_right").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=lrscan;sector=" + sector + ";xml", function() {
			$("#turns_available").html($("#lrscan_turns_available").val());
			$("#turns_used").html($("#lrscan_turns_used").val());
		});
	});
	
	// Zone description link
	$("#zone_description").live("click", function () {
		$("#maindisplay_right").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		var zone_id = $("#zone_id").val();
		$("#maindisplay_right").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=zoneinfo;zone=" + zone_id + ";xml");
	});
	
	// Warp movement buttons
	$(".warp_new_button, .warp_old_button").live("click", function () {
		var last_sector = "";
		var dest_sector = "";
		last_sector = $("#current_sector").val();
		dest_sector = $(this).text();
		$("#move_result").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Moving . . .' />");
		WarpMove(last_sector,dest_sector,"");
	});
	
	// Realspace movement links that use the anchor as a destination
	$(".rs_button, .rs_link").live("click", function () {
		var last_sector = "";
		var dest_sector = "";
		last_sector = $("#current_sector").val();
		dest_sector = $(this).text();
		$(this).html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Moving . . .' />");
		RSMove(last_sector,dest_sector,1,"");
	});
	
	// Realspace movement links that use input value as a destination
	$("#rs_input_engage").live("click", function () {
		$("#move_result").html("<img id='ajax_loading_icon' src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Moving . . .' />");
		var last_sector = "";
		var dest_sector = "";
		last_sector = $("#current_sector").val();
		dest_sector = $("#rs_moveto").val();
		RSMove(last_sector,dest_sector,1,"");
	});
	
	// Player confirmation of a realspace move,
	// Occurs when player has to spend more than 100 turns to make the move.
	$("#engage_2").live("click", function () {
		$("#move_result").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Moving . . .' />");
		var last_sector = "";
		var dest_sector = "";
		last_sector = $("#current_sector").val();
		dest_sector = $("#rs_moveto").val();
		RSMove(last_sector,dest_sector,2,"");
	});
	
	// Ship movement in a check fighter scenario
	$("#cf_action").live("click", function () {
		
		var last_sector = "";
		var dest_sector = "";
		var called_from = "";
		var response = "";
		
		last_sector = $("#cf_dest").val();
		dest_sector = $("#cf_sector").val();
		called_from = $("#cf_calledfrom").val();
		response = $("input:checked").val();
		$("#cf_form").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Moving . . .' />");
		if (called_from == "move")
		{
			WarpMove(last_sector,dest_sector,response);
		}
		else
		{
			RSMove(last_sector,dest_sector,1,response);
		}
	});
	
	// Galaxy map realspace links
	$(".galaxy_link").live("click", function () {
	
		var last_sector = "";
		var dest_sector = "";
		var triptime = "";
		var energy_scooped = "";
	
		last_sector = $("#current_sector").val();
		dest_sector = $(this).children("input").val();
		$(this).html("<img class='ajax_loader_small' src='" + smf_images_url + "/bnt/ajax-loader-small.gif'")
		move_result = $.ajax({
			type: "GET",
			async: false,
			url: smf_prepareScriptUrl(smf_scripturl),
			data: "action=blacknova;sa=rsmove;engage=1;destination=" + dest_sector + ";source=" + last_sector + ";xml"
		}).responseText;
		triptime = $(move_result).filter("#triptime").val();
		energy_scooped = $(move_result).filter("#energy_scooped").val();
		location.href = smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=main;last_sector=" + last_sector + ";triptime=" + triptime  + ";energy_scooped=" + energy_scooped + ";";
	});
	
	// Trade control buttons
	$("#tr_view").live("click", function () {
		$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;xml", function() {
			$("input:checkbox").createCheckboxRange();
		});
    });
	$("#tr_new").live("click", function () {
		$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;command=new;xml", function() {
			$("#tr_error_frame").hide();
		});
    });
	$("#tr_create").live("click", function () {
		var str = $("form").serialize();
		var validate_result = ValidateNewRoute(str);
		if (validate_result)
		{
			var create_result = $.ajax({
				type: "GET",
				async: false,
				url: smf_prepareScriptUrl(smf_scripturl),
				data: validate_result
			}).responseText;
			var status = $(create_result).filter("#status").val();
			if (status == "complete")
			{
				$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;command=display;xml", function() {
					$("#tr_results").html(create_result);
				});
			}
			else
			{
				$("#tr_error_frame").show();
				$("#tr_error_message").html(status);
			}
		}
    });
	$("#tr_settings").live("click", function () {
		$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;command=settings;xml");
    });
	$("#tr_setsettings").live("click", function () {
		if ($("#trade_colonists:checked").is(":checked"))
		{
			var trade_colonists = "Y";
		}
		else
		{
			var trade_colonists = "N";
		}
		if ($("#trade_fighters:checked").is(":checked"))
		{
			var trade_fighters = "Y";
		}
		else
		{
			var trade_fighters = "N";
		}
		if ($("#trade_torps:checked").is(":checked"))
		{
			var trade_torps = "Y";
		}
		else
		{
			var trade_torps = "N";
		}
		var trade_energy = $("input[name=trade_energy]:checked").val();
		var trade_shipid = $("#trade_shipid").val();
		$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;command=setsettings;trade_colonists=" + trade_colonists + ";trade_fighters=" + trade_fighters + ";trade_torps=" + trade_torps + ";trade_energy=" + trade_energy + ";trade_shipid=" + trade_shipid + ";xml");
    });
	$("#tr_delete").live("click", function () {
		var traderoute_id = $(this).children("input").val();
		$("#tr_dialog").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;command=delete;traderoute_id=" + traderoute_id + ";xml").dialog({ 
			modal: true,
			buttons: {	"Cancel": function() { 
									$(this).dialog("close"); 
									$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
									$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;xml");
								},
						"Delete": function() {
									$(this).dialog("close");
									$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
									var delete_result = $.ajax({
										type: "GET",
										async: false,
										url: smf_prepareScriptUrl(smf_scripturl),
										data: "action=blacknova;sa=traderoute;command=delete;traderoute_id=" + traderoute_id + ";confirm=yes;xml"
									}).responseText;
									$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;xml", function() {
										$("#tr_dialog").dialog(delete_result);
									});
								}
			}
		});
    });
	$("#tr_edit").live("click", function () {
		var traderoute_id = $(this).children("input").val();
		$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;command=edit;traderoute_id=" + traderoute_id + ";xml", function() {
			$("#tr_error_frame").hide();
		});
    });
	$("#tr_checkall").live("click", function () {
		$(":checkbox").attr("checked", $("#tr_checkall").is(":checked"));
	});
	
	// AJAX load button for traderoute engage from traderoute display
	$("#engage").live("click", function () {
		var id = $("input[name='traderoute_id']:checkbox").fieldArray();
		var runs = $("input:text").getValue();
		var engage = "";
		
		if (id == "")
		{
			alert("Please select at least one trade route");
		}
		else if  ((runs.length < 2) || (isPositiveInteger(runs.substring(1)) == false))
		{
			alert("Please enter the number of times you want to run the selected trade routes");
		}
		else
		{
			for (i = 0; i < id.length; i++)
			{
				engage = engage + id[i] + runs + ",";
			}
			engage = engage.substring(0, engage.length-1);
			TradeRouteLink(engage);
		}
	});
});

// Validate new trade route settings
function ValidateNewRoute(str)
{
	var arrString = str.split("&");
	$.NewRoute = new Object();
	var querystring = "action=blacknova;sa=traderoute;command=create";
	
	for (var i = 0, len = arrString.length; i < len; ++i)
	{
		arrTemp = arrString[i].split("=");
		$.NewRoute[arrTemp[0]] = arrTemp[1];
	}
	
	// Validate the source port type
	if ($.NewRoute.ptype1 == "port")
	{
		if ($.NewRoute.port_id1 == "")
		{
			alert("Please enter a source sector!");
			return false;
		}
		else if (!isPositiveInteger($.NewRoute.port_id1))
		{
			alert("Invalid sector!");
			return false;
		}
		else
		{
			querystring += ";ptype1=" + $.NewRoute.ptype1 + ";port_id1=" + $.NewRoute.port_id1;
		}
	}
	else if ($.NewRoute.ptype1 == "planet")
	{
		if ($.NewRoute.planet_id1 == "None")
		{
			alert("You have no personal planets!");
			return false;
		}
		else
		{
			querystring += ";ptype1=" + $.NewRoute.ptype1 + ";planet_id1=" + $.NewRoute.planet_id1;
		}
	}
	else if ($.NewRoute.ptype1 == "corp_planet")
	{
		if ($.NewRoute.corp_planet_id1 == "None")
		{
			alert("You have no corporate planets!");
			return false;
		}
		else
		{
			querystring += ";ptype1=" + $.NewRoute.ptype1 + ";corp_planet_id1=" + $.NewRoute.corp_planet_id1;
		}
	}
	else
	{
		alert("Please select a source!");
		return false;
	}
	
	// Validate the source port type
	if ($.NewRoute.ptype2 == "port")
	{
		if ($.NewRoute.port_id2 == "")
		{
			alert("Please enter a destination sector!");
			return false;
		}
		else if (!isPositiveInteger($.NewRoute.port_id2))
		{
			alert("Invalid sector!");
			return false;
		}
		else
		{
			querystring += ";ptype2=" + $.NewRoute.ptype2 + ";port_id2=" + $.NewRoute.port_id2;
		}
	}
	else if ($.NewRoute.ptype2 == "planet")
	{
		if ($.NewRoute.planet_id2 == "None")
		{
			alert("You have no personal planets!");
			return false;
		}
		else
		{
			querystring += ";ptype2=" + $.NewRoute.ptype2 + ";planet_id2=" + $.NewRoute.planet_id2;
		}
	}
	else if ($.NewRoute.ptype2 == "corp_planet")
	{
		if ($.NewRoute.corp_planet_id2 == "None")
		{
			alert("You have no corporate planets!");
			return false;
		}
		else
		{
			querystring += ";ptype2=" + $.NewRoute.ptype2 + ";corp_planet_id2=" + $.NewRoute.corp_planet_id2;
		}
	}
	else
	{
		alert("Please select a source!");
		return false;
	}
	
	// Check for Planet to Planet trades
	if (($.NewRoute.ptype1 == "planet" && $.NewRoute.ptype2 == "planet" || $.NewRoute.ptype2 == "corp_planet") 
		|| ($.NewRoute.ptype2 == "planet" && $.NewRoute.ptype1 == "planet" || $.NewRoute.ptype1 == "corp_planet"))
	{
		alert("Planet to Planet trading is not yet supported");
		return false;
	}
	
	// Check if this is a route edit
	if (typeof $.NewRoute.editing != "undefined")
	{
		querystring += ";editing=" + $.NewRoute.editing;
	}
	
	querystring += ";move_type=" + $.NewRoute.move_type + ";circuit_type=" + $.NewRoute.circuit_type + ";xml";
	return querystring;
}

// Warp Movement
function WarpMove(last_sector,dest_sector,response)
{
	var turns_used = "";
	var turns_avail = "";
	var status = "";
	
	// Run the move and store the results into move_result
	var move_result = $.ajax({
		type: "GET",
		async: false,
		url: smf_prepareScriptUrl(smf_scripturl),
		data: "action=blacknova;sa=move;sector=" + dest_sector + ";response=" + response + ";xml"
	}).responseText;
	
	// Extract data from the move_result ouput and store in variables
	turns_used = $(move_result).filter("#turns_used").val();
	turns_avail = $(move_result).filter("#turns_available").val();
	status = $(move_result).filter("#status").val();
	
	if (status == "complete")
	{
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=main;last_sector=" + last_sector + ";triptime=1;move_type=warp;xml", function() {
			$("#turns_available").html(turns_avail);
			$("#turns_used").html(turns_used);
		});
	}
	else if (status == "fighters")
	{
		$("#bnt_mainframe").html(move_result);
	}
	else if (status == "mines")
	{
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=main;last_sector=" + last_sector + ";triptime=1;move_type=warp;xml", function() {
			$("#turns_available").html(turns_avail);
			$("#turns_used").html(turns_used);
			$("#maindisplay_right").html(move_result);
		});
	}
	if (status == "retreat")
	{
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=main;xml", function() {
			$("#turns_available").html(turns_avail);
			$("#turns_used").html(turns_used);
			$("#move_result").html(move_result);
		});
	}
	else
	{
		$("#move_result").html(move_result);
	}
}

// RealSpace Movement
function RSMove(last_sector,dest_sector,engage,response)
{
	var turns_used = "";
	var turns_avail = "";
	var energy_scooped = "";
	var energy_total = "";
	var status = "";
	
	// Run the move and store the results into move_result
	var move_result = $.ajax({
		type: "GET",
		async: false,
		url: smf_prepareScriptUrl(smf_scripturl),
		data: "action=blacknova;sa=rsmove;engage=" + engage + ";destination=" + dest_sector + ";source=" + last_sector + ";response=" + response + ";xml"
	}).responseText;
	
	// Extract data from the move_result ouput and store in variables
	triptime = $(move_result).filter("#triptime").val();
	turns_used = $(move_result).filter("#turns_used").val();
	turns_avail = $(move_result).filter("#turns_available").val();
	energy_scooped = $(move_result).filter("#energy_scooped").val();
	energy_total = $(move_result).filter("#ship_energy").val();
	status = $(move_result).filter("#status").val();
	
	if (status == "complete")
	{
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=main;last_sector=" + last_sector + ";triptime=" + triptime  + ";energy_scooped=" + energy_scooped + ";move_type=rs;xml", function() {
			$("#turns_available").html(turns_avail);
			$("#turns_used").html(turns_used);
			$("#cargo_energy").html(energy_total);
		});
	}
	else if (status == "fighters")
	{
		$("#bnt_mainframe").html(move_result);
	}
	else if (status == "mines")
	{
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=main;last_sector=" + last_sector + ";triptime=" + triptime  + ";energy_scooped=" + energy_scooped + ";move_type=rs;xml", function() {
			$("#turns_available").html(turns_avail);
			$("#turns_used").html(turns_used);
			$("#cargo_energy").html(energy_total);
			$("#maindisplay_right").html(move_result);
		});
	}
	else if (status == "retreat")
	{
		$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=main;xml", function() {
			$("#turns_available").html(turns_avail);
			$("#turns_used").html(turns_used);
			$("#move_result").html(move_result);
		});
	}
	else
	{
		$("#move_result").html(move_result);
	}
}

// AJAX load link to initiate a Trade Route
function TradeRouteLink()
{
	var engage = "";
	
	for (i = 0; i < arguments.length; i++)
	{
		engage += arguments[i] + ",";
	}
	
	engage = engage.substring(0, engage.length-1);
	
	$("#bnt_mainframe").html("<img src='" + smf_images_url + "/bnt/ajax-loader.gif' alt='Loading . . .' />");
	$("#bnt_mainframe").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute;engage=" + engage + ";xml");
}
	
// Run all selected trade routes
function RunTradeRoute()
{	
	// If the function was called recurvisely, the arguments will be in an array
	if (isArray(arguments[0]) == true)
	{
		arrEngage = arguments[0];
		$.TradeRoute = {
			id: arrEngage[0],
			runs: arrEngage[1],
			routes: arrEngage.length,
			engage: ""
		}
		
		for (i = 2; i < arrEngage.length; i = i + 2)
		{
			$.TradeRoute.engage += arrEngage[i] + "," + arrEngage[i+1] + ",";
		}
		$.TradeRoute.engage = $.TradeRoute.engage.substring(0, $.TradeRoute.engage.length-1);
	}
	else
	{
		$.TradeRoute = {
			id: arguments[0],
			runs: arguments[1],
			routes: arguments.length,
			engage: ""
		}
		for (i = 2; i < arguments.length; i = i + 2)
		{
			$.TradeRoute.engage += arguments[i] + "," + arguments[i+1] + ",";
		}
		$.TradeRoute.engage = $.TradeRoute.engage.substring(0, $.TradeRoute.engage.length-1);
	}
	
	$("#tr_status").html("<img src=\'" + smf_images_url + "/bnt/ajax-loader.gif\' alt=\'Loading . . .\' />");
	$("#tr_output").load(smf_prepareScriptUrl(smf_scripturl) + "action=blacknova;sa=traderoute_engage;engage=" + $.TradeRoute.id + ";run=" + $.TradeRoute.runs + ";xml", function() {
		// Clear the status display, this may be the last run, don't want lingering animated gifs.
		$("#tr_status").html("");
		
		// Decrement the traderoute runs
		$.TradeRoute.runs--;
		
		// Get the traderoute results
		$.TradeRoute.source_type = $("#source_type").val();
		$.TradeRoute.source_sector = $("#source_sector").val();
		$.TradeRoute.source_result = $("#source_result").val();
		$.TradeRoute.source_scooped = $("#source_scooped").val();
		$.TradeRoute.source_profit = parseInt($("#source_profit").val());
		$.TradeRoute.dest_type = $("#dest_type").val();
		$.TradeRoute.dest_sector = $("#dest_sector").val();
		$.TradeRoute.dest_result = $("#dest_result").val();
		$.TradeRoute.dest_scooped = $("#dest_scooped").val();
		$.TradeRoute.dest_profit = parseInt($("#dest_profit").val());
		$.TradeRoute.single_run_profit = parseInt($("#single_run_profit").val());
		$.TradeRoute.single_run_turns = parseInt($("#single_run_turns").val());
		$.TradeRoute.playerinfo_ore = $("#playerinfo_ore").val();
		$.TradeRoute.playerinfo_organics = $("#playerinfo_organics").val();
		$.TradeRoute.playerinfo_goods = $("#playerinfo_goods").val();
		$.TradeRoute.playerinfo_energy = $("#playerinfo_energy").val();
		$.TradeRoute.playerinfo_colonists = $("#playerinfo_colonists").val();
		$.TradeRoute.playerinfo_fighters = $("#playerinfo_fighters").val();
		$.TradeRoute.playerinfo_torps = $("#playerinfo_torps").val();
		$.TradeRoute.playerinfo_credits = $("#playerinfo_credits").val();
		$.TradeRoute.playerinfo_turns = $("#playerinfo_turns").val();
		$.TradeRoute.playerinfo_turns_used = $("#playerinfo_turns_used").val();
		
		// Update the trade route results table
		$("#source_type_" + $.TradeRoute.id).html($.TradeRoute.source_type);
		$("#source_sector_" + $.TradeRoute.id).html($.TradeRoute.source_sector);
		$("#source_result_" + $.TradeRoute.id).html($.TradeRoute.source_result);
		$("#dest_type_" + $.TradeRoute.id).html($.TradeRoute.dest_type);
		$("#dest_sector_" + $.TradeRoute.id).html($.TradeRoute.dest_sector);
		$("#dest_result_" + $.TradeRoute.id).html($.TradeRoute.dest_result);
		
		// Update cargo and armament information
		$("#cargo_ore").html($.TradeRoute.playerinfo_ore);
		$("#cargo_organics").html($.TradeRoute.playerinfo_organics);
		$("#cargo_goods").html($.TradeRoute.playerinfo_goods);
		$("#cargo_energy").html($.TradeRoute.playerinfo_energy);
		$("#cargo_colonists").html($.TradeRoute.playerinfo_colonists);
		$("#armament_fighters").html($.TradeRoute.playerinfo_fighters);
		$("#armament_torps").html($.TradeRoute.playerinfo_torps);
		
		// Look for existing values in the single_run_turns_id cells so they can be added into the total.
		if ($("#single_run_turns_" + $.TradeRoute.id).html().length > 0)
		{
			$.TradeRoute.single_run_turns += parseInt($("#single_run_turns_" + $.TradeRoute.id).html());
			$("#single_run_turns_" + $.TradeRoute.id).html($.TradeRoute.single_run_turns);
		}
		else
		{
			$("#single_run_turns_" + $.TradeRoute.id).html($.TradeRoute.single_run_turns);
		}
		
		// Look for existing values in the single_run_profit_id so they can be added into the total.
		if ($("#single_run_profit_" + $.TradeRoute.id).html().length > 0)
		{
			$.TradeRoute.single_run_profit += parseInt($("#single_run_profit_" + $.TradeRoute.id).html());
			$("#single_run_profit_" + $.TradeRoute.id).html(addCommas($.TradeRoute.single_run_profit));
		}
		else
		{
			$("#single_run_profit_" + $.TradeRoute.id).html(addCommas($.TradeRoute.single_run_profit));
		}
		
		// Look for existing values in the total_turns so they can be added into the total.
		if ($("#total_turns").html().length > 0)
		{
			$.TradeRoute.total_turns = parseInt($("#total_turns").html());
			$.TradeRoute.total_turns += parseInt($("#single_run_turns").val());
			$("#total_turns").html($.TradeRoute.total_turns);
		}
		else
		{	
			$.TradeRoute.total_turns = parseInt($("#single_run_turns").val());
			$("#total_turns").html($.TradeRoute.total_turns);
		}
		
		// Look for existing values in the total_turns so they can be added into the total.
		if ($("#total_profit").html().length > 0)
		{
			$.TradeRoute.total_profit = parseInt(stripCommas($("#total_profit").html()));
			$.TradeRoute.total_profit += parseInt($("#single_run_profit").val());
			$("#total_profit").html(addCommas($.TradeRoute.total_profit));
		}
		else
		{	
			$.TradeRoute.total_profit = parseInt($("#single_run_profit").val());
			$("#total_profit").html(addCommas($.TradeRoute.total_profit));
		}
		
		$("#status_" + $.TradeRoute.id).html($.TradeRoute.runs);
		
		// Update the top and right menu items
		$("#turns_available").html($.TradeRoute.playerinfo_turns);
		$("#turns_used").html($.TradeRoute.playerinfo_turns_used);
		$("#cargo_credits").html($.TradeRoute.playerinfo_credits);
		
		// Check for an early trade stop condition
		var tradestop = false;
		if ($("#tradestop").length > 0)
		{
			tradestop = true;
		}
		
		// Check how many trade runs are left on this route
		if ($.TradeRoute.runs > 0 && tradestop == false)
		{
			// Have to convert the engage string to an array in order to properly pass arguments
			if ($.TradeRoute.engage == "")
			{
				$.TradeRoute.engage = new Array();
				$.TradeRoute.engage[0] = $.TradeRoute.id;
				$.TradeRoute.engage[1] = $.TradeRoute.runs;
			}
			else
			{
				var arrTemp = $.TradeRoute.engage.split(",");
				$.TradeRoute.engage = new Array();
				$.TradeRoute.engage[0] = $.TradeRoute.id;
				$.TradeRoute.engage[1] = $.TradeRoute.runs;
				$.TradeRoute.engage = $.TradeRoute.engage.concat(arrTemp);
			}
			RunTradeRoute($.TradeRoute.engage);
		}
		else
		{
			// Trade route is finished, mark complete on the display
			if (tradestop == false)
			{
				$("#status_" + $.TradeRoute.id).html("Complete");
			}
			// Early trade route stop detected, output the result
			else
			{
				$("#status_" + $.TradeRoute.id).html($("#tradestop").val());
			}
			
			// Check if there are more routes to run
			if ($.TradeRoute.routes > 2)
			{
				$.TradeRoute.engage = $.TradeRoute.engage.split(",");
				RunTradeRoute($.TradeRoute.engage);
			}
		}
	});
}

// Transferred from port.php
function makemax(name, val)
{
	var element = document.getElementById(name);
	if (element.value != val)
	{
		if (val != 0)
		{
			element.value = val;
		}
	}
}

// Transferred from port.php
function changeDelta(desiredvalue, currentvalue, upgradecost)
{
	Delta = 0; DeltaCost = 0;
	Delta = desiredvalue - currentvalue;

	while (Delta > 0) 
	{
		DeltaCost = DeltaCost + Math.pow(2,desiredvalue - Delta); 
		Delta = Delta - 1;
	}

	DeltaCost = DeltaCost * upgradecost
	return DeltaCost;
}

// Text fader
// Source: http://www.greywyvern.com/code/js/fade
function fadeObject(id, c1, c2, s1, s2) {
  var self = this;
  this.id      = id;
  this.elem    = false;
  this.colour  = {
    stt: [parseInt(c1.substr(0, 2), 16), parseInt(c1.substr(2, 2), 16), parseInt(c1.substr(4, 2), 16)],
    end: [parseInt(c2.substr(0, 2), 16), parseInt(c2.substr(2, 2), 16), parseInt(c2.substr(4, 2), 16)],
    now: [parseInt(c1.substr(0, 2), 16), parseInt(c1.substr(2, 2), 16), parseInt(c1.substr(4, 2), 16)]
  };
  this.steps   = [s1, s2];
  this.dir     = false;
  this.active  = false;
  this.queue   = [];
  this.msg     = [];
  this.message = 0;
  function d2h(num) {
    num = Math.round(num);
    return ((num < 16) ? "0" : "") + num.toString(16);
  }
  this.fade = function(message, direction) {
    this.elem = this.elem || document.getElementById(this.id);
    this.queue.push([message, direction]);
    for (var x = 0; x < this.queue.length; x++) {
      for (var y = x + 1; y < this.queue.length; y++) {
        if (this.queue[x][0] == this.queue[y][0] && this.queue[x][1] != this.queue[y][1]) {
          this.queue.splice(x, 1);
          this.queue.splice(y - 1, 1);
        }
      }
    }
    if (!this.active) setTimeout(function() { self.fadeLoop(); }, 10);
  };
  this.fadeLoop = function() {
    if (!this.active && this.queue.length) {
      if (this.dir && this.message != this.queue[0][0]) this.queue.unshift([this.message, false]);
      var msg = this.queue.shift();
      if (this.msg[msg[0]]) {
        this.active = true;
        this.elem.innerHTML = this.msg[this.message = msg[0]];
        this.dir = msg[1];
      }
    }
    if (this.dir) {
      var c1 = this.colour.stt, c2 = this.colour.end, s = this.steps[0];
    } else var c1 = this.colour.end, c2 = this.colour.stt, s = this.steps[1];
    for (var x = 0, cnow = "", inc = 0; x < 3; x++) {
      this.colour.now[x] += inc = (c2[x] - c1[x]) / s;
      cnow += this.colour.now[x] = (inc < 0) ? Math.max(this.colour.now[x], c2[x]) : Math.min(this.colour.now[x], c2[x]);
    } this.elem.style.color = "#" + d2h(this.colour.now[0]) + d2h(this.colour.now[1]) + d2h(this.colour.now[2]);
    if (cnow == c2.join("")) {
      this.active = false;
      if (!this.queue.length) {
        if (!this.dir) {
          if (this.msg[0]) {
            this.queue.push([0, true]);
            setTimeout(function() { self.fadeLoop(); }, 10);
          } else this.elem.innerHTML = "&nbsp;";
        }
      } else setTimeout(function() { self.fadeLoop(); }, 10);
    } else setTimeout(function() { self.fadeLoop(); }, 10);
  };
  if (window.addEventListener) {
    window.addEventListener('load', function() { self.fade(0, true); }, false); 
  } else if (window.attachEvent)
    window.attachEvent('onload', function() { self.fade(0, true); });
}

var hash = new Array();

function throb(item) {
 
	// If the hash array does not have an entry for this item, initialise it at 2
	if (!hash[item]) hash[item] = 2;

	// Send a fade command using the hash array to tell us what parameters we should use
	fader[item].fade(Math.floor(hash[item] / 2), !(hash[item] % 2));

	// Call this function again for this same item after a certain amount of time
	setTimeout(function() { throb(item); }, (hash[item] % 2) ? 100 : 15000);

	// If we have exceeded the number of messages in this fader, start over again at 2
	if (++hash[item] > fader[item].msg.length * 2 - 1) hash[item] = 2;
}

// Generic array test function
function isArray(obj)
{
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

// Generic string test for positive integer
function isPositiveInteger(s)
{
   return String(s).search(/^\d+$/) != -1
}

// Function to strip commas from a string
function stripCommas(numString)
{
    var re = /,/g;
    return numString.replace(re,"");
}

// Function to add commas to a string which contains an integer
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
